package cn.wyj.org.service.impl;

import cn.wyj.basic.config.BussinessException;
import cn.wyj.basic.query.BaseQuery;
import cn.wyj.basic.util.BaiduAuditUtils;
import cn.wyj.basic.util.PageList;
import cn.wyj.org.domain.Employee;
import cn.wyj.org.domain.Shop;
import cn.wyj.org.domain.ShopAuditLog;
import cn.wyj.org.mapper.EmployeeMapper;
import cn.wyj.org.mapper.ShopAuditLogMapper;
import cn.wyj.org.mapper.ShopMapper;
import cn.wyj.org.service.IShopAuditLogService;
import cn.wyj.org.service.IShopService;
import cn.wyj.basic.service.impl.BaseServiceImpl;
import cn.wyj.org.vo.ShopEchartsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import sun.net.www.HeaderParser;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.sound.midi.Soundbank;
import javax.swing.table.TableRowSorter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itsource
 * @since 2022-10-15
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper  shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    @Autowired
    private JavaMailSender sender;

    /**
     * 店铺入驻流程
     * @param shop
     */
    @Override
    public void settlement(Shop shop) {
        Employee admin = shop.getAdmin();
        // 通过校验方法，返回一个员工信息
        Employee employee = this.verify(shop, admin);

        // 存入数据了
        // 添加shop表
        shopMapper.add(shop);

        if (null == employee){
            // 添加emp
            employee = admin;
            employeeMapper.add(employee);
        }

        // 修改emp的shopid
        employee.setShopId(shop.getId());

        System.out.println(employee.getShopId());
        employeeMapper.update(employee);
        // 修改shop表的adminId
        Shop uptShop = new Shop();
        uptShop.setId(shop.getId());
        System.out.println(uptShop.getAdminId());
        uptShop.setAdminId(employee.getId());
        shopMapper.update(uptShop);


    }

    /**
     * 审核通过
     * @param shopAuditLog
     */
    @Override
    public void auditPass(ShopAuditLog shopAuditLog) {
        // 判断参数
        if (StringUtils.isBlank(shopAuditLog.getNote())){
            throw new BussinessException("备注不能为空！");
        }
        // 审核通过，将店铺状态修改为通过，也就是1
        Shop shop = new Shop();
        shop.setState(1);
        // 修改状态，还要传入ID
        shop.setId(shopAuditLog.getShopId());
        shopMapper.update(shop);

        // 将审核日志加入日志表
        // 审核人id写死
        shopAuditLog.setAuditId(324L);
        shopAuditLogMapper.add(shopAuditLog);

        // 给申请人发送邮件，回应申请结果
        // 创建复杂邮件对象
        MimeMessage mimeMessage = sender.createMimeMessage();

        // 发送复杂邮件的工具类
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("404438273@qq.com");

            helper.setSubject("宠物之家审核结果通知");
            // 设置文本内容，第二个参数true代表前面是不是一个html内容
            helper.setText("<h1>恭喜您审核您审核通过，点击下方链接激活店铺</h1>"
            + "http://localhost:8080/shop/active/" + shopAuditLog.getShopId(),true);

            helper.setTo("404438273@qq.com");
        } catch (Exception e) {
            throw new BussinessException("发送邮件错误!");

        }
        // 6.发送邮件
        sender.send(mimeMessage);


    }

    // 激活店铺
    @Override
    public void active(Long id) {
        Shop shop = new Shop();
        shop.setId(id);
        shop.setState(2);
        shopMapper.update(shop);
    }

    /**
     * 审核驳回
     * @param shopAuditLog
     */
    @Override
    public void auditReject(ShopAuditLog shopAuditLog) {
        // 判断参数
        if (StringUtils.isBlank(shopAuditLog.getNote())){
            throw new BussinessException("备注不能为空！");
        }
        // 修改商铺状态为-1，驳回状态，根据ID，前端有传入
        Shop shop = new Shop();
        shop.setId(shopAuditLog.getShopId());
        shop.setState(-1);
        shopMapper.update(shop);

        // 将操作信息存入日志表
        // 审核人先写死
        shopAuditLog.setAuditId(324L);
        shopAuditLogMapper.add(shopAuditLog);

        // 给商户返回邮件，告诉他申请被驳回
        // 创建一个复杂邮件对象
        MimeMessage mimeMessage = sender.createMimeMessage();
        //  发送复杂邮件的工具类
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage, true,"utf-8");
            // 设置发送人
            helper.setFrom("404438273@qq.com");
            //
            helper.setSubject("宠物之家审核结果通知");
            // 设置文本内容，
            helper.setText("您好，你的店铺审核未通过，请修改信息后重新提交！"+
                     "失败原因：'" + shopAuditLog.getNote() + "'," +
                    "修改链接：http://localhost:8081/#/registerAgain?shopId=" + shopAuditLog.getShopId()

                    );
            // 设置收信人
            helper.setTo("404438273@qq.com");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        sender.send(mimeMessage);

    }

    /**
     * 再次申请
     * @param
     */
    @Override
    public void auditAgain(Shop shop) {
        Employee admin = shop.getAdmin();

        // 校验名字为空
        if (StringUtils.isBlank(shop.getName())){
            throw new BussinessException("店铺名字不能为空");
        }

        // TODO AI验证
        Boolean boo = BaiduAuditUtils.TextCensor(shop.getName());

        if (!boo){
            throw new BussinessException("请输入合法信息");
        }

        if (!shop.getLogo().equals("")){
            Boolean boo2 = BaiduAuditUtils.ImgCensor(shop.getLogo());
            if (!boo2){
                throw new BussinessException("请输入合法Logo");
            }
        }

        // 判断店铺名字是否重复
        Shop tmpShop = shopMapper.findByName(shop.getName());
        if (null != tmpShop){
            throw new BussinessException("店铺已经存在！");
        }
        // 当前管理员是否管理了其他店铺
        Employee employee = employeeMapper.findByName(admin.getUsername());
        if (null != employee && null != employee.getShopId()){
            // 找到这个员工的shopids所对应的shop， 如果他的shopid不是空的话
            Shop shopById = shopMapper.findById(employee.getShopId());
            if (shopById.getAdminId().equals(employee.getId())){
                throw new BussinessException("当前管理员已经关联了店铺了！");
            }

        }

        shop.setState(1);
        shopMapper.update(shop);
    }

    // 报表
    @Override
    public Map<String, Object> echarts() {
        Map<String,Object> result = new HashMap<>();
        List<ShopEchartsVo> vo = shopMapper.echarts();

        List<Integer> x = vo.stream().map(ShopEchartsVo::getState).collect(Collectors.toList());
        List<Integer> y = vo.stream().map(ShopEchartsVo::getCount).collect(Collectors.toList());

        result.put("x",x);
        result.put("y",y);
        return result;
    }

    // 校验方法
    public Employee verify(Shop shop, Employee admin){

        // 校验名字为空
        if (StringUtils.isBlank(shop.getName())){
            throw new BussinessException("店铺名字不能为空");
        }

        // 校验两次密码是否一致
        if(!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BussinessException("两次密码不一致");
        }


        // TODO AI验证
        Boolean boo = BaiduAuditUtils.TextCensor(shop.getName());

        if (!boo){
            throw new BussinessException("请输入合法信息");
        }

        if (!shop.getLogo().equals("")){
            Boolean boo2 = BaiduAuditUtils.ImgCensor(shop.getLogo());
            if (!boo2){
                throw new BussinessException("请输入合法Logo");
            }
        }




        // 店铺名称是否存在
//        Shop tmpShop = shopMapper.findByName(shop.getName());
//        if (null!= tmpShop){
//            throw new BussinessException("店铺已经存在！");
//        }
        Shop tmpShop = shopMapper.findByName(shop.getName());
        if (null != tmpShop){
            throw new BussinessException("店铺已经存在！");
        }




        // 当前管理员是否管理了其他店铺
        Employee employee = employeeMapper.findByName(admin.getUsername());
        if (null != employee && null != employee.getShopId()){
            // 找到这个员工的shopids所对应的shop， 如果他的shopid不是空的话
            Shop shopById = shopMapper.findById(employee.getShopId());
            if (shopById.getAdminId().equals(employee.getId())){
                throw new BussinessException("当前管理员已经关联了店铺了！");
            }

        }

        return employee;
    }

    @Override
    public PageList<Shop> queryByPage(BaseQuery query) {
        PageList<Shop> shopPageList = super.queryByPage(query);

        // 判断非空
        if (null == shopPageList){
            throw new BussinessException("没有店铺！");
        }
        // 查询到的实体里有两个字段，一个是店铺的总条数，一个是店铺的实体集合
        // 获取到所有店铺的集合
        List<Shop> rows = shopPageList.getRows();

        // 把店铺集合的id集合取出来，id 就是shop的id
        List<Long> shopIds = rows.stream().map(Shop::getId).collect(Collectors.toList());

        // 根据shopIds去查询所有的日志集合
        List<ShopAuditLog> logList =  shopAuditLogMapper.findByShopId(shopIds);

        // 将logList集合根据shopId进行分组， key : shopId,   value : 日志集合
        HashMap<Long,List<ShopAuditLog>> logMap = new HashMap();

        for (ShopAuditLog log : logList) {
            // 通过Key取出map中的 value 也就是日志集合
            List<ShopAuditLog> temList = logMap.get(log.getShopId());
            // 这个日志集合可能为空，因为可能没有存
            if (CollectionUtils.isEmpty(temList)){
                temList = new ArrayList<>();
            }
            // 将shop的信息添加到日志集合中
            temList.add(log);
            // 将集合添加到分组里面，根据shopId来分组，如果当前shopId没有被创建就创建，如果有就覆盖
            logMap.put(log.getShopId(),temList);
        }
        rows.forEach(row->{
            row.setLogList(logMap.get(row.getId()));
        });


        return shopPageList;
    }
}
